package user

import (
	"gitee.com/zhanglibin/gmall/model"
	"gitee.com/zhanglibin/gmall/utils"

	"context"
	"errors"
	"fmt"
)

type User struct {
	Id       int    `json:"id"`
	Username string `json:"username"`
	Password string `json:"password"`
	Email    string `json:"email"`
	Avatar   string `json:"avatar"`
	Mobile   string `json:"mobile"`
}

func (User) TableName() string {
	return "user"
}

func Register(ctx context.Context, u *User) error {
	u.Password = utils.HashAndSalt([]byte(u.Password))
	result := model.Db.Create(u)
	if result.Error != nil {
		fmt.Println("ctx", ctx)
		fmt.Println("error", result.Error)
		return result.Error
	}

	return nil
}

func Login(ctx context.Context, u *User) error {
	var userInfo User
	err := model.Db.Where("username = ?", u.Username).First(&userInfo).Error
	if err != nil {
		return err
	}

	if !utils.ComparePwd(userInfo.Password, []byte(u.Password)) {
		return errors.New("密码错误")
	}

	return nil
}

func GetUserOneInfo(ctx context.Context, u *User) (User, error) {
	var userInfo User
	err := model.Db.Where(u).First(&userInfo).Error
	if err != nil {
		return userInfo, err
	}

	return userInfo, err
}

func GetUserList(ctx context.Context, page, pageSize int) (userList []User, count int64) {
	page = (page - 1) * pageSize
	model.Db.Count(&count)
	model.Db.Offset(page).Limit(pageSize).Order("id desc").Find(&userList)

	return userList, count
}

func Update(ctx context.Context, u *User) error {
	fmt.Println("==u", u)
	err := model.Db.Save(&u).Error
	return err
}
